//
//  EmoticonView.swift
//  01-表情键盘
//
//  Created by male on 15/10/23.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

//注册可充用的cell、
let emotionViewCellId  = "emotionViewCellId"

// MARK: 表情键盘视图
class EmoticonView: UIView {
    
    //该按钮添加监听方法
    @objc private func clickItem(item: UIBarButtonItem){
        
//        print(item.tag)
        
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        
        //滚动到对应的表情
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
    }
    
    //设置一个点击之后回调的属性
    private var selectedEmoticonCallBack: (emoticon: Emoticon)->()
    
    init(selectedEmoticon: (emoticon: Emoticon)->()) {
        // 记录闭包属性
          selectedEmoticonCallBack = selectedEmoticon
        
        // 调用父类的构造函数
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 236
        
        super.init(frame: rect)
        
        backgroundColor = UIColor.whiteColor()
        
        setupUI()
        
        // 滚动到第一页
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
    }

    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 懒加载控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: emotionViewFlowLayout())
    private lazy var toolbar = UIToolbar()
    
    private  let packages = EmoticonManager.shareManager.packages
    
     // MARK: 类中类只有在当前类中可以进行访问，其他的类是不能进行访问的
    private class emotionViewFlowLayout:UICollectionViewFlowLayout{
        
        private override func prepareLayout() {
            super.prepareLayout()
            
            super.prepareLayout()
            
            let col: CGFloat = 7
            let row: CGFloat = 3
            
            let w = collectionView!.bounds.width / col
            // 如果在 iPhone 4 的屏幕，只能显示两行
            let margin = (collectionView!.bounds.height - row * w) * 0.499
            
            itemSize = CGSize(width: w, height: w)
//            print(itemSize)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false

        }
    }
    
}
// MARK: - 设置界面
// private 修饰的 extension 内部的所有函数都是私有的
extension EmoticonView {
    
    /// 设置界面
    func setupUI() {
        // 1. 添加控件
        addSubview(toolbar)
        addSubview(collectionView)
        
        // 2. 自动布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toolbar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
        }
       
        // 3toolbar准备控件
        prepareForItem()
        prepareForCollectionCell()
    }
    //添加下面的toolbar小按钮
    private func prepareForItem(){
        
        //设置toolbar的颜色 
        toolbar.tintColor = UIColor.grayColor()
        
        var array = [UIBarButtonItem]()

        //设置标记 在使用toolbar的时候，它们都是功能相近的一组，所以可以使用tag进行区分
        var index = 0
        for p in packages{
            //添加标题
            array.append(UIBarButtonItem(title: p.group_name_cn, style: .Plain, target: self, action: "clickItem:"))
            array.last?.tag = index++
            //添加弹簧
            array.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil))
        }
        
        array.removeLast()
        //赋值
        toolbar.items = array
    }
    //准备collectioncell
    private func prepareForCollectionCell(){
        
        collectionView.backgroundColor = UIColor.lightGrayColor()
        
        //注册cell
        collectionView.registerClass(emotionViewCell.self, forCellWithReuseIdentifier: emotionViewCellId)
        
        //设置数据源
        collectionView.dataSource = self
        
        collectionView.delegate = self
    }
 
}

// MARK: collectionView 的数据源方法
extension EmoticonView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 获取表情模型
        let em = packages[indexPath.section].emoticons[indexPath.item]
        
        // 执行`回调`
        selectedEmoticonCallBack(emoticon: em)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
     func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        
        return packages[section].emoticons.count
    }

     func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emotionViewCellId, forIndexPath: indexPath) as! emotionViewCell
        
        cell.emotion = packages[indexPath.section].emoticons[indexPath.row]
        
        return cell
    }
}


// MARK: 自定义cell
class emotionViewCell :UICollectionViewCell{
    
    //表情模型
    var emotion:Emoticon?{
        didSet{
            emotionButton.setImage(UIImage(contentsOfFile: emotion!.imageUrl), forState: .Normal)
            
            emotionButton.setTitle(emotion?.emoji, forState: .Normal)
            
            if emotion!.isRemoved{
                emotionButton.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emotionButton)
        
        emotionButton.frame = CGRectInset(bounds, 4, 4)
        
        emotionButton.backgroundColor = UIColor.whiteColor()
        
        emotionButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
        
        emotionButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        emotionButton.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) { 
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载控件
    private lazy var emotionButton: UIButton = UIButton()
}





















